const jwt = require('jsonwebtoken')
const secret = require('./secret')

module.exports = {
    /* 加密 */
    sign(payload){
      const nobearer= jwt.sign(payload,secret)
      const bearer = 'Bearer ';
      return bearer.concat(nobearer) 
    },

    /* 解码 */

    decode(payload){
      
       const nobearer = payload.replace('Bearer ','')
        return jwt.decode(nobearer,secret)
    },
    // 解密并返回用户数据
    async getAccount(token,sql,syntax){
      
      try{
        let account =this.decode(token)
        
        syntax = syntax || "select * from nideshop_account where mobile=? and password=?";
      let result = await sql(syntax,[account.mobile,account.password])
      
      if(result.length > 0) return result
      
      Promise.reject('解码失败')
      }catch(err){
        Promise.reject('解码失败或者TOKEN过期')
      }
  }
}


 /* 测试加解码 */

// module.exports = ()=>{
//     /* 测试加解码 */
//     const se1 = jwt.sign('382818128qq',secret)
//     console.log(se1);

//     const de1 = jwt.decode(se1,secret)
//     console.log(de1,'这是解码后的');
// }